home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9301 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  68 lines

  1. Path: costello.SanDiegoCA.ATTGIS.COM!dle
  2. From: dle@costello.SanDiegoCA.ATTGIS.COM (Jake Le)
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Date: 29 Feb 1996 20:26:29 GMT
  6. Organization: AT&T Global Information Solutions-San Diego
  7. Distribution: world
  8. Message-ID: <4h525l$pja@rap.SanDiegoCA.ATTGIS.COM>
  9. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>
  10. NNTP-Posting-Host: costello.sandiegoca.attgis.com
  11.  
  12. Boris,
  13.  
  14. You can call the operator= in your copy constructor.
  15.  
  16. Here is an example:
  17.  
  18. class CFoo {
  19.  
  20. public:
  21.         CFoo() { m_iSize = 0; };
  22.         CFoo(const CFoo &foo)
  23.         {
  24.         // Call the operator=
  25.                 this->operator=(foo);
  26.         };
  27.  
  28.         CFoo& operator=(const CFoo &foo)
  29.         {
  30.                 m_iSize = foo.m_iSize;
  31.                 return *this;
  32.         };
  33.  
  34.         void Print() { cout << "Size = " << m_iSize << endl; };
  35.         void SetSize(int size) { m_iSize = size; };
  36.  
  37.         int m_iSize; // Hungarian notation
  38. };
  39.  
  40. Hope that help.
  41. --Jake
  42.  
  43. In article <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>, borisb@sd.znet.com (Boris Burtin) writes:
  44. |> I have noticed that a copy constructor and operator= perform pretty
  45. |> much the same function.  The code I wrote for my class simply copies
  46. |> each member variable from one class to the other.
  47. |> 
  48. |> Is there a way for the one of the two functions to call the other, to
  49. |> avoid duplicate code?  I have tried calling the copy constructor from
  50. |> operator=, but nothing happens.  I've gotten around this problem by
  51. |> creating a private Copy() function, which is called by both the copy
  52. |> constructor and operator=.  Is there another way?
  53. |> 
  54. |> Thanks,
  55. |> 
  56. |> Boris
  57. |> 
  58. |> 
  59.  
  60. -- 
  61. \\\======================================================================\\\
  62. \\\                 AT&T Global Information Solutions                    \\\
  63. \\\----------------------------------------------------------------------\\\
  64. \\\ Jake Q. Le                    || Jake.Le@SanDiegoCA.ATTGIS.COM       \\\
  65. \\\ 17089 Via Del Campo           || http://jakepc.SanDiegoCA.ATTGIS.COM \\\
  66. \\\ San Diego, CA 92127           ||                                     \\\
  67. \\\======================================================================\\\
  68.